import { login } from "../api/user";
import {tableSqls} from "../sql/tableSql";

export function objectToMap(data:any){
    return new Map(Object.entries(data)) as Map<string,any>
}

export function arrayToMap(data: any[]){
    // return data.map(it=>new Map(Object.entries(it))) as Map<string,any>[]
    let arr = new Array<Map<string,any>>()
    data.forEach(item=>{
        let a = new Map();
        let parse = JSON.parse(JSON.stringify(item));
        for( let k of Object.keys(parse)){
            a.set(k,parse[k])
        }
        arr.push(a)
    })
    return arr
}

const createQuery = (data:Map<string,any>) =>{
    if (data.size == 0){
        return ''
    }
    let querySql : any[] = []
    data.forEach((v,k)=>{
        if (typeof v == "string"){
            v = `'${v}'`
        }
        if (v != null && v != ''){
            querySql.push( k + ' = ' + v)
        }
    })
    return 'where ' + querySql.join(' and ')
}

const createSet = (data:Map<string,any>,key:String) =>{
    if (data.size == 0){
        return ''
    }
    let setSql : any[] = []
    data.forEach((v,k)=>{
        if (typeof v == "string"){
            v = `'${v}'`
        }
        if (v != null && k != 'id' && k != key){
            setSql.push( k + ' = ' + v)
        }
    })
    return setSql.join(',')
}

export function openSqlite() {
    return new Promise((resolve,reject) =>
        {
            plus.sqlite.openDatabase({
                name:'bigbug',  //数据库名称
                path:'_doc/bigbug.db',   //TODO 数据库地址，uniapp推荐以下划线为开头，这到底存在哪里去了，我也不清楚，哈哈
                success(e){
                    resolve(e); //成功回调
                },
                fail(e){                    
                    reject(e); //失败回调
                }
            })
        }
    )
}

export function createTable(tableSql:string[]){
    return new Promise((resolve, reject) => {
        plus.sqlite.executeSql({
            name:'bigbug',
            //表格创建或者打开，后面为表格结构
            sql:tableSql,
            success(e){
                resolve(e);
            },
            fail(e){
                reject(e);
            }
        })
    })
}

export function insertSql(tableName:String,data:Map<string,any> | Map<string,any>[] | undefined){
    return new Promise((resolve, reject)=>{
        let sql = ''
        if (data instanceof Map){
            let keys : string[] = []
            let vals : any[] = []
            data.forEach((value, key)=>{
                if (value != null&&typeof value != "object"){
                    vals.push(typeof value == "string" ? `'${value}'` : value)
                    keys.push(key)
                }
            })
            sql = `(${keys.join(',')}) values (${vals.join(',')})`
        }
        if (data instanceof Array){
            let keys : Set<string> = new Set<string>()
            let vals : string[] = []
            data.forEach(it=>{
                let val1 : any[] = []
                it.forEach((val,key)=>{
                    if (val == null&&keys.has(key)){

                    }
                    if (val != null){
                        keys.add(key)
                        val1.push(typeof val == "string" ? `'${val}'` : val)
                    }
                })
                vals.push(val1.join(','))
            })
            sql =  `(${Array.from(keys).join(',')}) values (${vals.join('),(')})`
        }
        plus.sqlite.executeSql({
            name:'bigbug',
            sql:[`insert into ${tableName} ${sql}`],
            success(e){
                resolve(e);
            },
            fail(e){
				console.log(e);
                reject(e);
            }
        })
    })
}

export function selectSql(tableName:String,queryParams:Map<string,any> | string = new Map(),order:string = ''){
    return new Promise((resolve, reject)=>{
        let query = ''
        if (typeof queryParams == "string"){
            query = queryParams
        }
        if (typeof queryParams == "object"){
            query = createQuery(queryParams)
        }
        plus.sqlite.selectSql({
            name:'bigbug',
            sql:`select * from ${tableName} ${query} ${order}`,
            success(e){
                resolve(e);
            },
            fail(e){
                reject(e);
            }
        })
    })
}

export function deleteSql(tableName:string,params:Map<string,any> | string){
    return new Promise((resolve, reject)=>{
        let delSql = ''
        if (typeof params != 'string'){
             delSql = createQuery(params)
        }
        if (typeof params =='string'){
            delSql = params
        }
        plus.sqlite.executeSql({
            name:'bigbug',
            sql:[`delete from ${tableName} ${delSql}`],
            success(e){
                resolve(e);
            },
            fail(e){
				console.log(e);
                reject(e);
            }
        })
    })
}

export function updateSql(tableName:string,data:Map<string,any>,query:string){
    return new Promise((resolve, reject)=>{
        let key = ''
        if (query != ''){
            let strs = query.split(' ')
            key = strs[1].trim()
        }
        let setSql = createSet(data,key)
        plus.sqlite.executeSql({
            name:'bigbug',
            sql:[`update ${tableName} set  ${setSql}  ${query}`],
            success(e){
                resolve(e);
            },
            fail(e){
                reject(e);
            }
        })
    })
}

export function isOpen(name:string = 'bigbug',path:string='_doc/bigbug.db'){
    //数据库打开了就返回true,否则返回false
    var open = plus.sqlite.isOpenDatabase({
        name:name,
        path:path
    })
    return open;
}

export function closeSQL(sqlName:string = 'bigbug'){
    return new Promise((resolve,reject) =>{
        plus.sqlite.closeDatabase({
            name:sqlName,
            success(e){
                resolve(e);
            },
            fail(e){
                reject(e);
            }
        })
    })
}
